import cv2 as cv
from matplotlib import pyplot as plt

img = cv.imread('coins.png', 0)
# 普通二值化
ret1, th1 = cv.threshold(img, 127, 255, cv.THRESH_BINARY)
# Otsu法二值化
ret2, th2 = cv.threshold(img, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)  # 随便给个0为阈值

images = [img, [], th1,
          img, [], th2]
titles = ['Original Image', 'Histogram', 'BINARY (v=127)',
          'Original Image', 'Histogram', 'OTSU(v=0)']
for i in range(2):
    plt.subplot(2, 3, i * 3 + 1), plt.imshow(images[i * 3], 'gray')
    plt.title(titles[i * 3]), plt.xticks([]), plt.yticks([])
    plt.subplot(2, 3, i * 3 + 2), plt.hist(images[i * 3].ravel(), 256)
    plt.title(titles[i * 3 + 1]), plt.xticks([]), plt.yticks([])
    plt.subplot(2, 3, i * 3 + 3), plt.imshow(images[i * 3 + 2], 'gray')
    plt.title(titles[i * 3 + 2]), plt.xticks([]), plt.yticks([])
plt.show()